<template>
    <div class="crm-receivable-container">
        <el-card shadow="hover" class="mb10" v-auth="'crm:receivable:list'">
            <el-form :inline="true" :model="search">
                <el-form-item>
                    <el-input v-model="search.contractCode" placeholder="请输入合同编号" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.contractName" placeholder="请输入合同名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.customerName" placeholder="请输入客户名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.receivableName" placeholder="请输入回款主题" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.examineStatus" placeholder="请选择审核状态" multiple clearable class="w100">
                        <el-option label="草稿" value="0"></el-option>
                        <el-option label="审核中" value="1"></el-option>
                        <el-option label="通过" value="2"></el-option>
                        <el-option label="驳回" value="3"></el-option>
                        <el-option label="撤回" value="4"></el-option>
                        <el-option label="作废" value="5"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.timefield" placeholder="请选择时间" class="w100">
                        <el-option label="创建时间" value="createTime"></el-option>
                        <el-option label="回款日期" value="paymentTime"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-date-picker type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                        unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-search" type="primary" @click="onTableSearch()">查询</el-button>
                    <el-button icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
                    <el-button v-if="!search.more" @click="onMoreSearch(true)" type="primary" link>更多</el-button>
                    <el-button v-if="search.more" @click="onMoreSearch(false)" type="info" link>收起</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="hover">
            <el-button v-auth="'crm:receivable:add'" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddCrmReceivable()">新增</el-button>
            <!-- <el-button v-auth="'crm:receivable:edit'" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditCrmReceivable()" :disabled="tableData.selections.length != 1">修改</el-button> -->
            <!-- <el-button v-auth="'crm:receivable:remove'" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button> -->
            <el-table ref="tableCrmReceivableRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column label="合同编号" prop="contractCode" width="150" show-overflow-tooltip></el-table-column>
                <el-table-column label="合同名称" prop="contractName" width="250" show-overflow-tooltip></el-table-column>
                <el-table-column label="回款主题" prop="receivableName" width="250" show-overflow-tooltip></el-table-column>
                <el-table-column label="客户名称" prop="customerName" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="回款日期" prop="paymentTime" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="回款方式" prop="paymentMethod" width="100" show-overflow-tooltip :formatter="loadPaymentMethod"></el-table-column>
                <el-table-column label="回款金额" prop="paymentAmount" width="150" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{scope.row.paymentAmount}} 元</span>
                    </template>
                </el-table-column>
                <el-table-column label="是否开票" prop="hasInvoice" show-overflow-tooltip>
                    <template #default="scope">
                        <span class="color-primary" v-if="scope.row.hasInvoice">是</span>
                        <span class="color-info" v-else>否</span>
                    </template>
                </el-table-column>
                <el-table-column label="审核状态" prop="examineStatus" width="80" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.examineStatus == '0'" class="color-primary">草稿</span>
                        <span v-else-if="scope.row.examineStatus == '1'" class="color-warning">审核中</span>
                        <span v-else-if="scope.row.examineStatus == '2'" class="color-success">通过</span>
                        <span v-else-if="scope.row.examineStatus == '3'" class="color-danger">驳回</span>
                        <span v-else-if="scope.row.examineStatus == '4'" class="color-primary">撤回</span>
                        <span v-else-if="scope.row.examineStatus == '5'" class="color-info">作废</span>
                    </template>
                </el-table-column>
                <el-table-column label="所属用户" prop="userName" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="所属部门" prop="deptName" width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" fixed="right" show-overflow-tooltip width="130" v-auths="['crm:receivable:info', 'crm:receivable:edit', 'crm:receivable:remove', 'crm:receivable:commited', 'crm:receivable:approved', 'crm:receivable:rejected', 'crm:receivable:canceled', 'crm:receivable:discard', 'crm:receivable:change']">
                    <template #default="scope">
                        <el-button v-auth="'crm:receivable:info'" type="primary" link @click="onOpenInfoCrmReceivable(scope.row)">详情</el-button>
                        <el-dropdown class="ml10" style="vertical-align:unset" v-auths="['crm:receivable:edit', 'crm:receivable:remove', 'crm:receivable:commited', 'crm:receivable:approved', 'crm:receivable:rejected', 'crm:receivable:canceled', 'crm:receivable:discard', 'crm:receivable:change']">
                            <span class="el-dropdown-link">
                                <el-button type="primary" link>更多 <i class="fa fa-angle-down"></i></el-button>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <div v-auth="'crm:receivable:edit'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenEditCrmReceivable(scope.row)">修改</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:receivable:remove'" v-show="['0','3','4','5'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onTabelRowDel(scope.row)">删除</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:receivable:commited'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '1')">提交</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:receivable:approved'" v-show="['1'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '2')">通过</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:receivable:rejected'" v-show="['1','2'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '3')">驳回</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:receivable:canceled'" v-show="['1'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '4')">撤回</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:receivable:discard'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '5')">作废</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:receivable:change'">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenChangeCrmReceivable(scope.row)">变更</el-button>
                                        </el-dropdown-item>
                                    </div>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.total"
            >
            </el-pagination>
        </el-card>
        <AddCrmReceivable ref="addCrmReceivableRef" @submit="onTableSearch"/>
        <EditCrmReceivable ref="editCrmReceivableRef" @submit="onTableSearch"/>
        <ChangeCrmReceivable ref="changeCrmReceivableRef" @submit="onTableSearch"/>
        <InfoCrmReceivable ref="infoCrmReceivableRef"></InfoCrmReceivable>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddCrmReceivable from '/@/views/crm/receivable/addCrmReceivable.vue';
import EditCrmReceivable from '/@/views/crm/receivable/editCrmReceivable.vue';
import ChangeCrmReceivable from '/@/views/crm/receivable/changeCrmReceivable.vue';
import InfoCrmReceivable from '/@/views/crm/receivable/infoCrmReceivable.vue';
import { getCrmReceivableList, delCrmReceivable, examineCrmReceivable } from '/@/api/crm/receivable/index';
import { getDictionaryByLabel } from '/@/api/system/dictionary/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
export default {
    name: 'crm/receivable',
    components: { AddCrmReceivable, EditCrmReceivable, ChangeCrmReceivable, InfoCrmReceivable },
    setup() {
        const tableCrmReceivableRef = ref();
        const addCrmReceivableRef = ref();
        const editCrmReceivableRef = ref();
        const changeCrmReceivableRef = ref();
        const infoCrmReceivableRef = ref();
        const state = reactive({
            paymentMethods: [],
            search:{
                contractCode: undefined,
                contractName: undefined,
                customerName: undefined,
                receivableName: undefined,
                examineStatus: [],
                timefield: 'createTime',
                startTime: '',
                endTime: '',
                orderBy: 'createTime',
				isAsc: 'desc',
                pageNum: 1,
                pageSize: 10,
                more: false,
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false
            }
        });

        const loadTableData = (params) => {
            const search = { ...state.search, ...params };
            const examineStatusStr = search.examineStatus.join(',');
            getCrmReceivableList({
                ...search,
                examineStatus: examineStatusStr
            }).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableCrmReceivableRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
            state.search.contractCode = undefined;
            state.search.contractName = undefined;
            state.search.customerName = undefined;
            state.search.receivableName = undefined;
            state.search.examineStatus = [];
            state.search.startTime = undefined;
            state.search.endTime = undefined;
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        const onMoreSearch = (more: boolean) => {
            state.search.more = more;
        };
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
        // 打开新增弹窗
        const onOpenAddCrmReceivable = (row: object) => {
            addCrmReceivableRef.value.openDialog(row);
        };
        // 打开编辑弹窗
        const onOpenEditCrmReceivable = (row: object) => {
            row = row || state.tableData.selections[0];
            editCrmReceivableRef.value.openDialog(row);
        };
        // 打开变更弹窗
        const onOpenChangeCrmReceivable = (row: object) => {
            row = row || state.tableData.selections[0];
            changeCrmReceivableRef.value.openDialog(row);
        };
        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的回款信息信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delCrmReceivable(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条回款信息信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delCrmReceivable([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };
        
        const loadPaymentMethod = (row, column, cellValue, index) => {
            return state.paymentMethods.find((item) => item.dictValue == cellValue)?.dictName;
        }

        const examineStatusText = (status: String) => {
            const statusMap = {
                '0': '草稿',
                '1': '提交',
                '2': '通过',
                '3': '驳回',
                '4': '撤回',
                '5': '作废'
            };
            return statusMap[status] || '未知';
        };

        const onOpenExamineRecordStatus = (row: object, status: String) => {
            if(['1', '2', '4', '5'].includes(status)){
                ElMessageBox.confirm(`确认【${ examineStatusText(status) }】操作吗？`, '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    examineCrmReceivable({ examineTargetId: row.id, status: status }).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('操作成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }else{
                ElMessageBox.prompt('请输入驳回原因：', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then((message) => {
                    if (!message.value || message.value.trim() === '') {
                        ElMessage.error('驳回原因不能为空，请重新输入！');
                    } else {
                        examineCrmReceivable({ examineTargetId: row.id, status: status, examineReason: message.value }).then((res) => {
                            if(res.code === 0){
                                ElMessage.success('操作成功');
                                loadTableData({});
                            }
                        });
                    }
                }).catch(() => {});
            }
        };
        
        const onOpenInfoCrmReceivable = (row: object) => {
            row = row || state.tableData.selections[0];
            infoCrmReceivableRef.value.openDialog(row);
        };

        // 页面加载时
        onMounted(() => {
            loadTableData({});
            getDictionaryByLabel({ dictLabel: 'crm_payment_method' }).then((res: any) => {
                if (res.code == 0) {
                    state.paymentMethods = res.data;
                }
            });
        });
        return {
            tableCrmReceivableRef,
            addCrmReceivableRef,
            editCrmReceivableRef,
            changeCrmReceivableRef,
            infoCrmReceivableRef,
            onTableSearch,
            onResetSearch,
            onMoreSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onOpenAddCrmReceivable,
            onOpenEditCrmReceivable,
            onTabelRowsDel,
            onTabelRowDel,
            loadPaymentMethod,
            onOpenExamineRecordStatus,
            onOpenInfoCrmReceivable,
            onOpenChangeCrmReceivable,
            ...toRefs(state),
        };
    },
};
</script>